package com.qzboot.backend.web.module.sys.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.qzboot.backend.web.common.config.SysLog;
import com.qzboot.backend.web.module.sys.BaseSysController;
import com.qzboot.common.constant.SysConst;
import com.qzboot.common.support.WebResult;
import com.qzboot.facade.common.MpSupport;
import com.qzboot.facade.entity.SysUser;
import com.qzboot.facade.entity.SysUserToken;
import com.qzboot.facade.service.SysUserService;
import com.qzboot.facade.service.SysUserTokenService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author zengzhihong
 * @date 2019-12-19
 */
@RestController
@RequestMapping("/sysUserToken")
public class SysUserTokenController extends BaseSysController {


    @Reference
    private SysUserTokenService sysUserTokenService;
    @Reference
    private SysUserService sysUserService;

    /**
     * 分页查询
     *
     * @param param
     * @return
     */
    @GetMapping("/listPage")
    @RequiresPermissions("sys:userToken:list")
    public WebResult listPage(@RequestParam Map<String, Object> param) {
        param.put("expireTime", MpSupport.GE + DateUtil.now());
        return WebResult.success(sysUserTokenService.page(param));
    }

    /**
     * 移除登录状态
     *
     * @param id
     * @return
     */
    @SysLog("移除登录状态")
    @GetMapping("/removeById")
    @RequiresPermissions("sys:userToken:delete")
    public WebResult removeById(Long id) {
        SysUserToken sysUserToken = sysUserTokenService.getById(id);
        Assert.notNull(sysUserToken, "记录不存在");
        SysUser sysUser = sysUserService.getById(sysUserToken.getUserId());
        if (!SysConst.ADMIN_USER_ID.equals(getUserId())) {
            Assert.isTrue(!SysConst.ADMIN_USER_ID.equals(sysUserToken.getUserId()), "无权操作内置管理员");
            Assert.isTrue(sysUser.getCreateByUserId().equals(sysUserToken.getUserId()), "无权操作");
        }
        sysUserTokenService.removeById(id);
        return WebResult.success();
    }
}
